package com.wavehi.web.homework;

import com.wavehi.web.BaseServlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author WaveHi
 * @Date 22/9/2021 下午 7:07
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description Demonstrate how to deal the case that Http have no state in cookie.
 */
@WebServlet("/homework02Servlet")
public class Homework02Servlet extends BaseServlet {
    protected void base(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
    protected void showContent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取邮件内容
        String content = "Email content";
        //将邮件内容绑定到请求域的数据
        req.setAttribute("content", content);
        //获取请求转发对象
        RequestDispatcher dis = req.getRequestDispatcher("/page/homework02/email_content.jsp");
        //转发
        dis.forward(req, resp);
    }
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取登录信息
        String username = req.getParameter("username").trim();
        String password = req.getParameter("password").trim();
        //验证登录信息
        boolean exist = "admin".equals(username) && "admin".equalsIgnoreCase(password);
        //转发相应页面
        if(exist) {
            //获取cookie对象
            Cookie usernameCookie = new Cookie("username", username);
            //调整cookie对象
            usernameCookie.setMaxAge(60 * 60 * 24 * 7);
            usernameCookie.setPath("/");
            //向浏览器回传cookie信息
            resp.addCookie(usernameCookie);
            //获取转发对象
            RequestDispatcher dis = req.getRequestDispatcher("/page/homework02/index.jsp");
            //转发
            dis.forward(req, resp);
        }else {
            //设置错误信息信息
            req.setAttribute("errorMsg", "Username or password is not right");
            //获取转发对象
            RequestDispatcher dis = req.getRequestDispatcher("/page/homework02/login.jsp");
            //转发
            dis.forward(req, resp);
        }
    }
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取所有邮件
        List<String> list = Arrays.asList("Email01", "Email02", "Email03", "Email04");
        //绑定请求域数据
        req.setAttribute("list", list);
        //获取请求转发对象
        RequestDispatcher dis = req.getRequestDispatcher("/page/homework02/email_display.jsp");
        //转发
        dis.forward(req, resp);
    }
}
